package com.lhkj.ct.wechat.controller;

import com.lhkj.ct.base.constants.ConfigConstants;
import com.lhkj.ct.base.enums.IamsServiceEnum;
import com.lhkj.ct.base.utils.http.HttpUtils;
import com.lhkj.ct.meta.admin.service.SysConfigService;
import com.lhkj.ct.wechat.SignUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号消息回调接口
 */
@Controller
@RequestMapping("/wechat")
public class WechatMessageController {
    private static Logger logger = LoggerFactory.getLogger(WechatMessageController.class);

    @Resource
    private SysConfigService sysConfigService;

    /**
     * @param @param request
     * @param @param response
     * @param @param signature
     * @param @param timestamp
     * @param @param nonce
     * @param @param echostr
     * @Description: 用于接收get参数，返回验证参数
     * @author dapengniao
     * @date 2016年3月4日 下午6:20:00
     */
    @RequestMapping(value = "security", method = RequestMethod.GET)
    public void doGet(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "signature", required = true) String signature,
            @RequestParam(value = "timestamp", required = true) String timestamp,
            @RequestParam(value = "nonce", required = true) String nonce,
            @RequestParam(value = "echostr", required = true) String echostr) {
        try {
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                PrintWriter out = response.getWriter();
                out.print(echostr);
                out.close();
            } else {
                logger.info("这里存在非法请求！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "security", method = RequestMethod.POST, produces = "application/xml; charset=UTF-8")
    // post方法用于接收微信服务端消息
    public String DoPost(HttpServletResponse response,
                         HttpServletRequest request,
                         @RequestBody String requestBody,
                         @RequestParam("signature") String signature,
                         @RequestParam("timestamp") String timestamp,
                         @RequestParam("nonce") String nonce,
                         @RequestParam(name = "encrypt_type", required = false) String encType,
                         @RequestParam(name = "msg_signature", required = false) String msgSignature
                    ) throws IOException {
        logger.info("接收到微信服务端消息, {}", requestBody);
        logger.info("接收到微信服务端消息通过工具转换, {}", IOUtils.toString(request.getInputStream()));
//        //微信加密签名
//        String signature = request.getParameter("signature");
//        //时间戳
//        String timestamp = request.getParameter("timestamp");
//        //随机数
//        String nonce = request.getParameter("nonce");
//        // 消息签名
//        String msgSignature = request.getParameter("msg_signature");
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            Map<String, Object> params = new HashMap<>();
            params.put("message", IOUtils.toString(request.getInputStream()));
            params.put("msgSignature", msgSignature);
            params.put("nonce", nonce);
            params.put("encType", "aes");
            params.put("timestamp", timestamp);
            String url = UriComponentsBuilder.newInstance()
                    .scheme("http")
                    .host("127.0.0.1")
                    .port(9090)
                    .path(IamsServiceEnum.WECHAT_MESSAGE_URL.getUrl())
                    .queryParam("mp_id", sysConfigService.selectConfigByKey(ConfigConstants.SYS_WECHAT_APPID))
                    .queryParam("msg_signature", msgSignature)
                    .queryParam("signature", signature)
                    .queryParam("encrypt_type", encType)
                    .queryParam("timestamp", timestamp)
                    .queryParam("nonce", nonce)
                    .build()
                    .toUriString();
            return HttpUtils.sendPost(url, requestBody);
        } else {
            logger.info("这里存在非法请求！");
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }
    }


}

